ActiveAdmin.register Timetables::Provisional do
  filter :company_name, as: :string, label: '集团'
  filter :store_name, as: :string, label: '门店'
  filter :coach_name, as: :string, label: '教练'
  filter :course_name, as: :string, label: '课程'
  filter :class_start_time
  filter :class_end_time

  actions :index, :show, :destroy
  index do
    selectable_column
    column :id
    column '门店' do |item|
      item.store.try(:name)
    end
    column '课程' do |item|
      item.course.try(:name)
    end
    column '教练' do |item|
      item.coach.name
    end
    column '上课时间', :class_start_time
    column '下课时间', :class_end_time
    column '价格' do |item|
      status_tag("版权费: #{item.pricing.fetch("copyright", 0)}", class: :purple)
      status_tag("等级费: #{item.pricing.fetch("grade", 0)}", class: :pink)
      status_tag("补贴: #{item.pricing.fetch("perquisite", 0)}", class: :green)
      status_tag("服务费: #{item.pricing.fetch("service", 0)}", class: :error)
    end
    actions
  end

  controller do
    def scoped_collection
      Timetables::Provisional.includes(:store, :course, :coach)
    end

    def index
      if params[:format].eql?("csv") || params[:format].eql?("xls")
        sql =  Timetables::Provisional.ransack(params[:q]).result.to_sql
        filter = sql.split("WHERE")[1]
        book = Spreadsheet::Workbook.new
        sheet = book.create_worksheet
        sheet.name = '预发布课表'
        sheet.row(0).concat(%w(门店 课程 教练 上课时间 下课时间 版权费 课时费 补贴 服务费))
        Timetables::Provisional.joins(:store, :course, :coach).where(filter).pluck(
          Arel.sql(
            "stores.name, CASE courses.name WHEN courses.en_name THEN courses.name ELSE CONCAT(courses.name,'|',courses.en_name) END,
                coaches.en_name, class_start_time, class_end_time, pricing->>'copyright', pricing->>'grade', pricing->>'perquisite', pricing->>'service'"
          )
        ).each do |column|
          sheet.row(sheet.row_count).concat(column)
        end
        stream = StringIO.new('')
        book.write(stream)
        send_data(
          stream.string,
          filename: "预发布课程-#{Time.now.to_i}.xls",
          type: Mime::Type.lookup_by_extension(:xls)
        )
      else
        index!
      end
    end
  end
end
